package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.uu.utils.uuUtils;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.AddImageAdapter;
import com.hemaapp.yjnh.bean.AfterSale;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.Img;
import com.hemaapp.yjnh.bean.ImgItemsBean;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.view.DeliveryDialog;
import com.hemaapp.yjnh.view.ImageGridView;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import xtom.frame.util.XtomToastUtil;

/**
 * 买家和卖家的售后详情
 */
public class AfterSalesDetailActivity extends BaseActivity implements OnClickListener {

    @Bind(R.id.title_left_btn)
    ImageButton titleLeftBtn;
    @Bind(R.id.title_right_btn)
    Button titleRightBtn;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.iv_state)
    ImageView ivState;
    @Bind(R.id.tv_state)
    TextView tvState;
    @Bind(R.id.tv_fee)
    TextView tvFee;
    @Bind(R.id.tv_stamp)
    TextView tvStamp;
    @Bind(R.id.tv_date)
    TextView tvDate;
    @Bind(R.id.tv_reason)
    TextView tvReason;
    @Bind(R.id.tv_description)
    TextView tvDescription;
    @Bind(R.id.line_image)
    View lineImage;
    @Bind(R.id.image_grid)
    ImageGridView imageGrid;
    @Bind(R.id.tv_apply_date)
    TextView tvApplyDate;
    @Bind(R.id.tv_order_no)
    TextView tvOrderNo;
    @Bind(R.id.line_bottom)
    View lineBottom;
    @Bind(R.id.layout_bottom)
    LinearLayout layoutBottom;
    @Bind(R.id.tv_refuse_return)
    TextView tvRefuseReturn;
    @Bind(R.id.tv_agree_return)
    TextView tvAgreeReturn;
    @Bind(R.id.tv_receive)
    TextView tvReceive;
    @Bind(R.id.tv_return)
    TextView tvReturn;
    @Bind(R.id.tv_cancel_apply)
    TextView tvCancelApply;
    @Bind(R.id.tv_hint_fee)
    TextView tvHintFee;
    @Bind(R.id.tv_hint_stamp)
    TextView tvHintStamp;
    @Bind(R.id.tv_hint_date)
    TextView tvHintDate;

    private String orderId;
    private AfterSale afterSale;
    private AddImageAdapter imageAdapter;
    ArrayList<ImgItemsBean> replyImgs = new ArrayList<>();
    private User user;
    private boolean isSeller = false;//是卖家端还是买家端:true卖，false买

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_aftersale_detail);
        ButterKnife.bind(this);
        user = getApplicationContext().getUser();
        super.onCreate(savedInstanceState);
        if (isSeller) {
            getNetWorker().getFarmerAfterDetail(user.getToken(), orderId);
        } else if (user != null) {
            getNetWorker().getAfterSalesDtl(user.getToken(), orderId);
        }
    }

    @Override
    protected void findView() {
    }

    @Override
    protected void getExras() {
        isSeller = mIntent.getBooleanExtra("isSeller", false);
        orderId = mIntent.getStringExtra("order_id");
        if (isNull(orderId)) {//如果id也为空，那么就返回
            XtomToastUtil.showShortToast(mContext, "获取信息失败");
            titleText.postDelayed(new Runnable() {

                @Override
                public void run() {
                    finish();
                }
            }, 1000);
        }
    }

    @Override
    protected void setListener() {
        titleText.setText("退款详情");
        titleRightBtn.setVisibility(View.GONE);
    }

    private void setDatas() {
        //重置
        layoutBottom.setVisibility(View.GONE);
        tvRefuseReturn.setVisibility(View.GONE);
        tvAgreeReturn.setVisibility(View.GONE);
        tvReturn.setVisibility(View.GONE);
        tvReceive.setVisibility(View.GONE);

        double price = Double.valueOf(afterSale.getPrice());
        double count = Double.valueOf(afterSale.getBuycount());
        double stamp = Double.valueOf(afterSale.getScore());
        double freight = Double.valueOf(afterSale.getShipping_fee());
        double totalCash = (price - stamp) * count+freight;
        tvFee.setText("¥"+uuUtils.formatAfterDot2(totalCash+"") + "（含运费¥"+uuUtils.formatAfterDot2(freight+"") + "）");
        tvStamp.setText(uuUtils.formatAfterDot2(stamp * count + ""));

        String itemtype = afterSale.getItemtype();
        // 状态	0正常;1申请中;2等待买家发货;3拒绝;4退货中;5退货完成
        if (itemtype.equals("1")) {
            ivState.setImageResource(R.drawable.right_grey);
            tvState.setText("审核中");
            tvDate.setText("");
            layoutBottom.setVisibility(View.VISIBLE);
            if (isSeller) {
                tvRefuseReturn.setVisibility(View.VISIBLE);
                tvAgreeReturn.setVisibility(View.VISIBLE);
            } else {
                tvCancelApply.setVisibility(View.VISIBLE);
            }
        } else if (itemtype.equals("2")) {
            ivState.setImageResource(R.drawable.right_green);
            tvState.setText("待退货");
            tvDate.setText("");
            if (isSeller)
                layoutBottom.setVisibility(View.GONE);
            else {
                layoutBottom.setVisibility(View.VISIBLE);
                tvReturn.setVisibility(View.VISIBLE);
            }
        } else if (itemtype.equals("3")) {
            ivState.setImageResource(R.drawable.bg_cancel_grey);
            tvState.setText("商家拒绝退款");
            tvHintStamp.setVisibility(View.GONE);
            tvStamp.setVisibility(View.GONE);
            tvHintFee.setText("拒绝原因:");
            tvFee.setText(afterSale.getMemo());
            tvHintDate.setText("拒绝时间:");
            tvDate.setText(afterSale.getHandledate());
            layoutBottom.setVisibility(View.GONE);
        } else if (itemtype.equals("4")) {
            ivState.setImageResource(R.drawable.right_green);
            tvState.setText("退货中");
            tvDate.setText("");
            if (isSeller) {
                layoutBottom.setVisibility(View.VISIBLE);
                tvReceive.setVisibility(View.VISIBLE);
            } else
                layoutBottom.setVisibility(View.GONE);
        } else if (itemtype.equals("5")) {
            ivState.setImageResource(R.drawable.right_green);
            tvState.setText("退款成功");
            tvDate.setText(afterSale.getHandledate());
            layoutBottom.setVisibility(View.GONE);
        }
        //通用，买家申请退款的信息
        tvReason.setText(afterSale.getReason());
        tvDescription.setText(afterSale.getDescription());
        tvApplyDate.setText(afterSale.getApplydate());
        tvOrderNo.setText(afterSale.getBill_sn());
        //添加显示图片
        replyImgs.clear();
        String imgBig0 = afterSale.getImgurl0();
        if (!isNull(imgBig0)) {
            ImgItemsBean img0 = new ImgItemsBean();
            img0.setImgurl(afterSale.getImgurl0());
            img0.setImgurlbig(afterSale.getImgurl0big());
            replyImgs.add(img0);
        }

        String imgBig1 = afterSale.getImgurl1();
        if (!isNull(imgBig1)) {
            ImgItemsBean img1 = new ImgItemsBean();
            img1.setImgurl(afterSale.getImgurl1());
            img1.setImgurlbig(afterSale.getImgurl1big());
            replyImgs.add(img1);
        }

        String imgBig2 = afterSale.getImgurl2();
        if (!isNull(imgBig2)) {
            ImgItemsBean img2 = new ImgItemsBean();
            img2.setImgurl(afterSale.getImgurl2());
            img2.setImgurlbig(afterSale.getImgurl2big());
            replyImgs.add(img2);
        }

        String imgBig3 = afterSale.getImgurl3();
        if (!isNull(imgBig3)) {
            ImgItemsBean img3 = new ImgItemsBean();
            img3.setImgurl(afterSale.getImgurl3());
            img3.setImgurlbig(afterSale.getImgurl3big());
            replyImgs.add(img3);
        }
        if (replyImgs.size() > 0) {
            imageGrid.setVisibility(View.VISIBLE);
            refreshImages();
        }else
            imageGrid.setVisibility(View.GONE);
    }

    private void refreshImages() {
        if (imageAdapter == null) {
            imageAdapter = new AddImageAdapter(mContext, replyImgs);
            imageGrid.setAdapter(imageAdapter);
            imageAdapter.setShowDelete(false);
            imageAdapter.setShowAdd(false);
            imageAdapter.setImageClickListener(new AddImageAdapter.OnImageClickListener() {
                @Override
                public void onImageClickListener(int position) {
                    ArrayList<Img> imgs = new ArrayList<Img>();
                    for (int i = 0; i < replyImgs.size(); i++) {
                        ImgItemsBean item = replyImgs.get(i);
                        String imgurl_detail = item.getImgurlbig();
                        Img img = new Img(imgurl_detail);
                        imgs.add(img);
                    }

                    Intent intent = new Intent();
                    intent.setClass(mContext, ShowLargeImageActivity.class);
                    intent.putExtra("imgs", imgs);
                    intent.putExtra("position", position + 1);
                    mContext.startActivity(intent);
                }

                @Override
                public void onDeleteClickListener(int position, ImgItemsBean imageItem) {
                }
            });
        } else {
            imageAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case ORDER_SAVEOPERATE:
            case SALE_SUPPORT_GET:
            case FARMER_AFTERSERVICE_GET:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case ORDER_SAVEOPERATE:
            case SALE_SUPPORT_GET:
            case FARMER_AFTERSERVICE_GET:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case FARMER_AFTERSERVICE_GET:
            case SALE_SUPPORT_GET:
                HemaArrayResult<AfterSale> aResult = (HemaArrayResult<AfterSale>) baseResult;
                afterSale = aResult.getObjects().get(0);
                if (afterSale != null) {
                    setDatas();
                } else {
                    XtomToastUtil.showShortToast(mContext, "获取信息失败");
                    titleText.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            finish();
                        }
                    }, 1000);
                }
                break;
            case ORDER_SAVEOPERATE:
                String keytype = netTask.getParams().get("keytype");
                if (keytype.equals("11")) {
                    XtomToastUtil.showShortToast(mContext, "您已拒绝退款");
                } else if (keytype.equals("10")) {
                    XtomToastUtil.showShortToast(mContext, "您已同意退款，等待买家退货");
                } else if (keytype.equals("12")) {
                    XtomToastUtil.showShortToast(mContext, "发货成功");
                } else if (keytype.equals("13")) {
                    XtomToastUtil.showShortToast(mContext, "确认收货成功");
                } else if (keytype.equals("8")) {
                    XtomToastUtil.showShortToast(mContext, "撤销申请成功");
                    setResult(RESULT_OK);
                    finish();
                    return;
                }
                //重新获取数据
                if (isSeller) {
                    getNetWorker().getFarmerAfterDetail(user.getToken(), orderId);
                } else if (user != null) {
                    getNetWorker().getAfterSalesDtl(user.getToken(), orderId);
                }
                EventBusMsg msg = new EventBusMsg();
                msg.setType(EventBusConfig.UPDATE_ORDER);
                EventBus.getDefault().post(msg);
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case ORDER_SAVEOPERATE:
                XtomToastUtil.showShortToast(mContext, "操作失败，" + baseResult.getMsg());
                break;
            case SALE_SUPPORT_GET:
            case FARMER_AFTERSERVICE_GET:
                XtomToastUtil.showShortToast(mContext, "获取信息失败，" + baseResult.getMsg());
                titleText.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case ORDER_SAVEOPERATE:
                XtomToastUtil.showShortToast(mContext, "操作失败，请稍后再试");
                break;
            case SALE_SUPPORT_GET:
            case FARMER_AFTERSERVICE_GET:
                XtomToastUtil.showShortToast(mContext, "获取信息失败，请稍后再试");
                titleText.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
                break;
        }
    }

    @OnClick({R.id.title_left_btn, R.id.tv_refuse_return, R.id.tv_agree_return,
            R.id.tv_receive, R.id.tv_return, R.id.tv_cancel_apply})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.tv_refuse_return:
                HemaButtonDialog dailog1 = new HemaButtonDialog(mContext);
                dailog1.setText("确定拒绝买家的售后吗？");
                dailog1.setLeftButtonText("取消");
                dailog1.setRightButtonText("确定");
                dailog1.setRightButtonTextColor(getResources().getColor(R.color.theme_orange));
                dailog1.setButtonListener(new HemaButtonDialog.OnButtonListener() {

                    @Override
                    public void onRightButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                        getNetWorker().orderSaveoperate(user.getToken(), afterSale.getId(), "11", "无",
                                "无", "无", "无");
                    }

                    @Override
                    public void onLeftButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                    }
                });
                break;
            case R.id.tv_agree_return:
                HemaButtonDialog dailog2 = new HemaButtonDialog(mContext);
                dailog2.setText("确定同意买家的售后吗？");
                dailog2.setLeftButtonText("取消");
                dailog2.setRightButtonText("确定");
                dailog2.setRightButtonTextColor(getResources().getColor(R.color.theme_orange));
                dailog2.setButtonListener(new HemaButtonDialog.OnButtonListener() {

                    @Override
                    public void onRightButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                        getNetWorker().orderSaveoperate(user.getToken(), afterSale.getId(), "10", "无",
                                "无", "无", "无");
                    }

                    @Override
                    public void onLeftButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                    }
                });
                break;
            case R.id.tv_receive:
                HemaButtonDialog dailog3 = new HemaButtonDialog(mContext);
                dailog3.setText("确认收货后，将退款给买家");
                dailog3.setLeftButtonText("取消");
                dailog3.setRightButtonText("确定");
                dailog3.setButtonListener(new HemaButtonDialog.OnButtonListener() {

                    @Override
                    public void onRightButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                        getNetWorker().orderSaveoperate(user.getToken(), afterSale.getId(), "13", "无",
                                "无", "无", "无");
                    }

                    @Override
                    public void onLeftButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                    }
                });
                break;
            case R.id.tv_return:
                final DeliveryDialog deliveryDialog = new DeliveryDialog(mContext).builder();
                deliveryDialog.setClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String expressName = deliveryDialog.getExpressName();
                        String expressNum = deliveryDialog.getExpressNum();
                        if (isNull(expressName)) {
                            XtomToastUtil.showShortToast(mContext, "快递公司名称不能为空!");
                            return;
                        }
                        if (expressNum.isEmpty()) {
                            XtomToastUtil.showShortToast(mContext, "快递单号不能为空!");
                            return;
                        }
                        getNetWorker().orderSaveoperate(user.getToken(), afterSale.getId(), "12", "无",
                                "无", expressName, expressNum);
                        deliveryDialog.dismiss();
                    }
                });
                deliveryDialog.show();
                break;
            case R.id.tv_cancel_apply:
                HemaButtonDialog dailog4 = new HemaButtonDialog(mContext);
                dailog4.setText("确定撤销申请吗？");
                dailog4.setLeftButtonText("取消");
                dailog4.setRightButtonText("确定");
                dailog4.setButtonListener(new HemaButtonDialog.OnButtonListener() {

                    @Override
                    public void onRightButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                        getNetWorker().orderSaveoperate(user.getToken(), afterSale.getId(), "8", "无",
                                "无", "无", "无");
                    }

                    @Override
                    public void onLeftButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                    }
                });
                break;
        }
    }
}
